<template>
  <div class="p-4">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="font-semibold text-lg">商品分类管理</h3>
          <el-button type="primary" @click="handleAddCategory">
            <el-icon><Plus /></el-icon>
            <span>添加分类</span>
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选区域 -->
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 分类树表格 -->
      <el-table
        :data="categoryList"
        stripe
        border
        fit
        highlight-current-row
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="name" label="分类名称" min-width="200">
          <template #default="scope">
            <div class="flex items-center">
              <span v-if="scope.row.level > 1" class="mr-2">
                <span v-for="i in scope.row.level - 1" :key="i" class="inline-block w-6 h-px bg-gray-300"></span>
              </span>
              <el-icon v-if="scope.row.children && scope.row.children.length > 0" class="mr-2">
                <Folder />
              </el-icon>
              <el-icon v-else class="mr-2">
                <Document />
              </el-icon>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.sort" 
              :min="1" 
              :precision="0" 
              size="small"
              @change="handleSortChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#10b981"
              inactive-color="#e5e7eb"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEditCategory(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteCategory(scope.row)"
              :disabled="scope.row.children && scope.row.children.length > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑分类' : '添加分类'" :width="500">
      <template #default>
        <el-form
          ref="categoryFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          class="form-container"
        >
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="上级分类" prop="parentId">
            <el-select 
              v-model="formData.parentId" 
              placeholder="请选择上级分类"
              :disabled="isEditMode && !hasParentOption"
            >
              <el-option label="无" value="0" />
              <el-option 
                v-for="category in categoryOptions" 
                :key="category.id" 
                :label="category.name" 
                :value="category.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number 
              v-model="formData.sort" 
              :min="1" 
              :precision="0" 
              placeholder="请输入排序值" 
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="分类图标" prop="icon">
            <el-input v-model="formData.icon" placeholder="请输入图标类名（可选）" />
            <div class="mt-2 text-sm text-gray-500">
              支持Font Awesome图标，例如：fa-shopping-bag
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </el-form-item>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Folder, Document } from '@element-plus/icons-vue'

// 模拟分类数据
const mockCategories = [
  { 
    id: 1, 
    name: '电子数码', 
    parentId: 0, 
    level: 1,
    sort: 1, 
    status: 1,
    icon: 'fa-mobile',
    createTime: '2023-01-01 10:00:00',
    children: [
      { 
        id: 101, 
        name: '手机', 
        parentId: 1, 
        level: 2,
        sort: 1, 
        status: 1,
        icon: 'fa-mobile-phone',
        createTime: '2023-01-02 14:30:00',
        children: []
      },
      { 
        id: 102, 
        name: '电脑', 
        parentId: 1, 
        level: 2,
        sort: 2, 
        status: 1,
        icon: 'fa-laptop',
        createTime: '2023-01-03 09:15:00',
        children: []
      }
    ]
  },
  { 
    id: 2, 
    name: '服装鞋帽', 
    parentId: 0, 
    level: 1,
    sort: 2, 
    status: 1,
    icon: 'fa-tshirt',
    createTime: '2023-01-04 16:45:00',
    children: [
      { 
        id: 201, 
        name: '男装', 
        parentId: 2, 
        level: 2,
        sort: 1, 
        status: 1,
        icon: 'fa-male',
        createTime: '2023-01-05 11:20:00',
        children: []
      },
      { 
        id: 202, 
        name: '女装', 
        parentId: 2, 
        level: 2,
        sort: 2, 
        status: 1,
        icon: 'fa-female',
        createTime: '2023-01-06 15:30:00',
        children: []
      }
    ]
  },
  { 
    id: 3, 
    name: '家居用品', 
    parentId: 0, 
    level: 1,
    sort: 3, 
    status: 1,
    icon: 'fa-home',
    createTime: '2023-01-07 10:15:00',
    children: []
  },
  { 
    id: 4, 
    name: '食品饮料', 
    parentId: 0, 
    level: 1,
    sort: 4, 
    status: 0,
    icon: 'fa-cutlery',
    createTime: '2023-01-08 14:20:00',
    children: []
  }
]

// 状态管理
const categoryList = ref([])
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const localCategories = ref([...mockCategories])

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  parentId: 0,
  sort: 1,
  status: 1,
  icon: ''
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 1, message: '排序值必须大于等于1', trigger: 'blur' },
    { type: 'integer', message: '排序值必须为整数', trigger: 'blur' }
  ]
})

// 表单引用
const categoryFormRef = ref(null)

// 是否有父级分类选项
const hasParentOption = computed(() => {
  return categoryOptions.value.length > 0
})

// 分类选项列表（用于下拉选择）
const categoryOptions = computed(() => {
  const options = []
  
  // 扁平化分类树
  function flattenCategories(categories, level = 0) {
    categories.forEach(category => {
      // 排除当前编辑的分类及其子分类
      if (isEditMode.value && category.id === formData.id) {
        return
      }
      
      const prefix = '|-- '.repeat(level)
      options.push({
        id: category.id,
        name: `${prefix}${category.name}`,
        level: level + 1
      })
      
      if (category.children && category.children.length > 0) {
        flattenCategories(category.children, level + 1)
      }
    })
  }
  
  flattenCategories(localCategories.value)
  return options
})

// 获取分类列表
const fetchCategoryList = () => {
  // 应用搜索筛选
  let filtered = [...localCategories.value]
  
  if (searchForm.name) {
    // 递归筛选包含搜索关键词的分类及其父级分类
    function filterCategories(categories) {
      const result = []
      
      categories.forEach(category => {
        const hasMatch = category.name.includes(searchForm.name)
        const childrenMatch = category.children && category.children.length > 0 
          ? filterCategories(category.children) 
          : []
          
        if (hasMatch || childrenMatch.length > 0) {
          result.push({
            ...category,
            children: childrenMatch
          })
        }
      })
      
      return result
    }
    
    filtered = filterCategories(filtered)
  }
  
  // 复制到列表数据
  categoryList.value = JSON.parse(JSON.stringify(filtered))
  
  // 更新总数（扁平化后的总数）
  function countCategories(categories) {
    let count = 0
    categories.forEach(category => {
      count++
      if (category.children && category.children.length > 0) {
        count += countCategories(category.children)
      }
    })
    return count
  }
  
  total.value = countCategories(filtered)
}

// 搜索分类
const handleSearch = () => {
  currentPage.value = 1
  fetchCategoryList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  currentPage.value = 1
  fetchCategoryList()
}

// 添加分类
const handleAddCategory = () => {
  isEditMode.value = false
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'parentId' || key === 'sort' || key === 'status' ? 
                   (key === 'status' ? 1 : 0) : ''
  })
  dialogVisible.value = true
  nextTick(() => {
    categoryFormRef.value?.resetFields()
  })
}

// 编辑分类
const handleEditCategory = (row) => {
  isEditMode.value = true
  // 复制数据到表单
  Object.keys(formData).forEach(key => {
    formData[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('请先删除该分类下的所有子分类')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除分类"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 递归查找并删除分类
      function deleteCategory(categories, id) {
        const index = categories.findIndex(item => item.id === id)
        if (index !== -1) {
          categories.splice(index, 1)
          return true
        }
        
        for (const category of categories) {
          if (category.children && category.children.length > 0) {
            if (deleteCategory(category.children, id)) {
              return true
            }
          }
        }
        
        return false
      }
      
      if (deleteCategory(localCategories.value, row.id)) {
        ElMessage.success('删除成功')
        fetchCategoryList()
      } else {
        ElMessage.error('分类不存在')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 提交表单
const submitForm = () => {
  categoryFormRef.value?.validate(valid => {
    if (!valid) return false

    if (isEditMode.value) {
      // 更新分类
      function updateCategory(categories) {
        for (let i = 0; i < categories.length; i++) {
          if (categories[i].id === formData.id) {
            // 防止将自己设为父级分类
            if (formData.id === formData.parentId) {
              ElMessage.error('不能将自己设为父级分类')
              return false
            }
            
            categories[i] = { ...categories[i], ...formData }
            return true
          }
          
          if (categories[i].children && categories[i].children.length > 0) {
            if (updateCategory(categories[i].children)) {
              return true
            }
          }
        }
        
        return false
      }
      
      if (updateCategory(localCategories.value)) {
        ElMessage.success('更新成功')
      } else {
        ElMessage.error('分类不存在')
      }
    } else {
      // 添加分类
      const newId = Math.max(...localCategories.value.map(item => item.id), 0) + 1
      
      // 查找父级分类
      function findParentCategory(categories, parentId) {
        if (parentId === 0) return null
        
        for (const category of categories) {
          if (category.id === parentId) {
            return category
          }
          
          if (category.children && category.children.length > 0) {
            const result = findParentCategory(category.children, parentId)
            if (result) return result
          }
        }
        
        return null
      }
      
      const parentCategory = findParentCategory(localCategories.value, formData.parentId)
      
      // 计算层级
      const level = parentCategory ? parentCategory.level + 1 : 1
      
      // 创建新分类
      const newCategory = {
        ...formData,
        id: newId,
        level: level,
        createTime: new Date().toLocaleString(),
        children: []
      }
      
      if (parentCategory) {
        parentCategory.children.push(newCategory)
      } else {
        localCategories.value.push(newCategory)
      }
      
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    fetchCategoryList()
  })
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchCategoryList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchCategoryList()
}

// 排序值改变
const handleSortChange = (row) => {
  // 这里可以添加排序值变化后的处理逻辑
  // 实际项目中可能需要调用API更新排序
  fetchCategoryList()
}

// 状态改变
const handleStatusChange = (row) => {
  // 这里可以添加状态变化后的处理逻辑
  // 实际项目中可能需要调用API更新状态
  ElMessage.success(`分类"${row.name}"状态已更新`)
}

// 生命周期钩子
onMounted(() => {
  fetchCategoryList()
})
</script>

<style scoped>
/* 自定义样式 */
.form-container {
  padding: 10px 0;
}
</style>